import random,string


from django.contrib.auth.models import User, Group
from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet, ViewSet
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.status import HTTP_404_NOT_FOUND
from utils.customPermissions import TeacherPermission
# Create your views here.
from school.models import Classes
from .serializers import ClassesSerializer
from user.serializers import CreateUserSerializer
from celery_tasks.email.tasks import send_mail_task


class ClassesViewSet(ModelViewSet):
    queryset = Classes.objects.filter(is_delete=False)
    serializer_class = ClassesSerializer
    # permission_classes = [IsAuthenticated]  # 使用内置的登录权限
    permission_classes = [TeacherPermission]


class ClassesMemberViewSet(ViewSet):
    serializer_class = CreateUserSerializer
    permission_classes = [TeacherPermission]

    def add_member(self,request,pk):
        """
        1.获取指定班级
        2.判断成员是否已经属于改班级，属于，返回提示'该成员已经加入了该班级’ 代码终止
        3.不属于,判断成员是否注册，已注册，添加班级 代码终止
        4.未注册，注册用户，生成初始密码
        5.新账户放到学生组并添加班级
        6.通过邮件将账户初始密码发送给学生邮箱
        :param request:
        :param pk: 班级id
        :return:
        """
        # 1.获取指定班级
        try:
            classes = Classes.objects.get(id=pk)
        except Classes.DoesNotExist:
            return Response(status = HTTP_404_NOT_FOUND)
        # 2.判断成员是否已经属于改班级，属于，返回提示'该成员已经加入了该班级’ 代码终止
        username = request.data['username']
        member = classes.member.filter(username= username)
        if member:
            # 属于
            return Response({'msg':'该成员已经加入了该班级'})

        # 3.不属于, 判断成员是否注册，已注册，添加班级代码终止
        user = User.objects.filter(username= username)
        if user:
            # 注册
            classes.member.add(user[0])
            return Response(ClassesSerializer(user[0]).data)
        # 4.未注册，注册用户，生成初始密码
        user_serializer = CreateUserSerializer(data=request.data)
        user_serializer.is_valid(raise_exception=True) #数据校验

        first_name = request.data['first_name']
        email=request.data['email']

        user =User(username=username,email=email,first_name=first_name)
        # 生成初始密码
        source = string.ascii_letters+string.digits

        password = ''.join(random.sample(source,6))
        user.set_password(password) # 密码密文保存
        user.save()

        # 5.新账户放到学生组并添加班级
        group = Group.objects.get(id=2)
        group.user_set.add(user) # 反向，学生组
        classes.member.add(user) # 正向，添加班级

        # 6.通过邮件将账户初始密码发送给学生邮箱
        send_mail_task.delay(email, username , password , classes.name) # 调用delay方法，提交一个异步任务到队列中

        return Response(user_serializer.data)

